package com.mike.bdb.util;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.mike.bdb.manager.DBManager;

public class JSONUtil {
	
	/** 对象转jsonObject String */
	public static String getJSONObjStr(Object o) {
		JSONObject json = new JSONObject();
		
		String curStoreClazz = DataCurrent.getInstance().curStoreClazz;
		if(null == curStoreClazz) return null;
		
		Class<?> storeClazz = DPLBDBNameUtil.getInstance().getClassByName(curStoreClazz);
		if(null == storeClazz) return null;
		
		List<Method> berkeleyAttribute = ReflectUtil.getBerkeleyAttribute(storeClazz);
		try {
			for (Method m : berkeleyAttribute) {
				Object invoke = m.invoke(o, null);
				//key 方法名字	value 值 
				json.put(m.getName(), invoke.toString());
				
			}
		} catch (Exception e) {
			//ignore
		}
		return json.toString();
	}
	
	/** String 对象转jsonObject */
	public static void getJSONObjStr(String jsonObjStr, HashMap<String, Type> methodReturnMap) {
		if(null == jsonObjStr || "".equals(jsonObjStr.trim())) return;
		if(null == methodReturnMap) return;
		try {
			JSONObject jsObject = new JSONObject(jsonObjStr);
			
			String curStoreClazz = DataCurrent.getInstance().curStoreClazz;
			if(null == curStoreClazz) return;
			
			Class<Object> classBy = ReflectUtil.getClassBy(curStoreClazz);
			if(null == classBy) return;
			
			Object newInstance = classBy.newInstance();
			Iterator keys = jsObject.keys();
			while(keys.hasNext()) {
				Object next = keys.next();
				Object object = jsObject.get(next.toString());
				ReflectUtil.invokeSet(curStoreClazz, next.toString(), newInstance, object.toString(), methodReturnMap, false);
			}
			
			Class pkClass = ReflectUtil.getPKClass(classBy);
			DBManager.getInstance().getPKStore(pkClass, classBy).put(newInstance);
		} catch (JSONException e) {
			//ignore
		} catch (InstantiationException e) {
		} catch (IllegalAccessException e) {
		}
	}
}
